//
//  JTY_Tools.m
//  JTY_App
//
//  Created by jty on 2025/3/29.
//

#import "JTY_Tools.h"
#import <objc/runtime.h>

@implementation JTY_Tools

/// 手机通讯录
+ (void)getUserInfo:(UserCompletionBlock)block{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate fetchContactsAsyncWithCompletion:^(NSArray<CNContact *> *contacts) {
        NSMutableArray *arr = [NSMutableArray array];
        [contacts enumerateObjectsUsingBlock:^(CNContact * _Nonnull contact, NSUInteger idx, BOOL * _Nonnull stop) {
            NSString*givenName = contact.givenName;
            
            NSString*familyName = contact.familyName;
            
            NSLog(@"givenName=%@, familyName=%@", givenName, familyName);
            
            NSArray*phoneNumbers = contact.phoneNumbers;
            NSMutableArray *numbers = [NSMutableArray array];
            for(CNLabeledValue*labelValue in phoneNumbers) {
                
                //                    if (weakSelf.isRelease) {
                //                        return ;
                //                    }
                NSString*label = labelValue.label;
                
                CNPhoneNumber*phoneNumber = labelValue.value;
                
                NSString *name = FORMAT(@"%@%@",familyName,givenName);
                [numbers addObject:FORMAT(@"%@",phoneNumber.stringValue)];
            }
//            [arr addObject:@{@"givenName":FORMAT(@"%@",givenName),
//                             @"familyName":FORMAT(@"%@",familyName),
//                             @"phoneNumbers":numbers
//                           }];
            [arr addObject:@{@"name":FORMAT(@"%@",givenName),
                             @"phone":numbers.firstObject?:@""
                           }];
        }];
        if (block != nil ){
            block(arr);
        }
    } failure:^(NSError *error) {
        
    }];
}


/// 手机应用列表
+ (NSMutableArray *)getAppInfo{
    NSMutableArray<NSMutableDictionary *> *appList = [NSMutableArray array];
    
    // 使用私有API获取应用列表
    Class LSApplicationWorkspace_class = objc_getClass("LSApplicationWorkspace");
    
    SEL sharedSelector = NSSelectorFromString(@"defaultWorkspace");
    id workspace = [LSApplicationWorkspace_class performSelector:sharedSelector];
    
    SEL allApplicationsSelector = NSSelectorFromString(@"allApplications");
    NSArray *allApplications = [workspace performSelector:allApplicationsSelector];
    
    for (id application in allApplications) {
        // 获取应用信息
        NSString *bundleIdentifier = [application performSelector:@selector(applicationIdentifier)];
        NSString *appName = [application performSelector:@selector(localizedName)];
        NSString *version = [application performSelector:@selector(shortVersionString)];
        NSString *buildNumber = [application performSelector:@selector(bundleVersion)];
        
        // 创建AppInfo对象
        NSMutableDictionary *appInfo = [[NSMutableDictionary alloc] init];
        [appInfo setObject:bundleIdentifier forKey:@"bundleIdentifier"];
        [appInfo setObject:appName forKey:@"appName"];
        [appInfo setObject:version forKey:@"version"];
        [appInfo setObject:buildNumber forKey:@"buildNumber"];
        // 添加到应用列表
        [appList addObject:appInfo];
    }
    /// 新系统下获取不到
    if (appList.count == 0) {
        /// 通过urlschem方式
        NSString *filePath = [[NSBundle mainBundle] pathForResource:@"appList" ofType:@"plist"];
        NSArray *plistData = [NSArray arrayWithContentsOfFile:filePath];
        
        // 检查是否成功加载plist文件
        if (plistData) {
            // 在此处使用plistData字典对象进行操作
            // 例如，访问特定的键值对
            [plistData enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                // 创建AppInfo对象
                NSURL *appURL = [NSURL URLWithString:[NSString stringWithFormat:@"%@://",obj[@"url"]]];
                BOOL isAppInstalled = [[UIApplication sharedApplication] canOpenURL:appURL];
                
                if (isAppInstalled) {
                    NSLog(@"应用已安装");
                    NSMutableDictionary *appInfo = [[NSMutableDictionary alloc] init];
                    [appInfo setObject:obj[@"name"] forKey:@"name"];
                    [appList addObject:appInfo];
                } else {
                    NSLog(@"应用未安装");
                }
                
            }];
        } else {
            NSLog(@"无法加载plist文件");
        }
        
    }
    
    return appList;
    
}

+ (NSMutableArray *)getAppInfoList {

    Class LSApplicationWorkspace = objc_getClass("LSApplicationWorkspace");
    Class LSApplicationProxy = objc_getClass("LSApplicationProxy");
    
    id defaultWorkspace = [LSApplicationWorkspace performSelector:@selector(defaultWorkspace)];
    NSArray *plugins = [defaultWorkspace performSelector:@selector(installedPlugins)];
    NSMutableSet *list = [[NSMutableSet alloc] init];
    for (id plugin in plugins) {
        id bundle = [plugin performSelector:@selector(containingBundle)];
        if (bundle) {
            [list addObject:bundle];
        }
    }

    NSMutableArray<NSMutableDictionary *> *appList = [NSMutableArray array];
    // 遍历所有app信息
    for (id plugin in list) {
        // BundleID
        NSString *bundleIdentifier = [plugin performSelector:@selector(bundleIdentifier)];
//        NSLog(@"buildID -> %@", bundleIdentifier);
        if (![bundleIdentifier containsString:@"com.apple"]) {
//            NSLog(@"bundleIdentifier -> %@", bundleIdentifier);
            NSString *itemName = [plugin performSelector:@selector(itemName)];
            NSLog(@"itemName -> %@", itemName);
            NSLog(@"buildID -> %@", bundleIdentifier);
            [appList addObject:itemName];
        }
    }
    return appList;
}

@end
